const Koa = require('koa')
const app = new Koa()
const shell = require('child_process')
app.use(async ctx=>{
  // 
  if (ctx.url=== '/', ctx.method === 'POST') {
    console.log("has connection join")
    let postData = await parsePostData(ctx)
    if (postData.password == 'demos') {
      // 执行shell脚本
      shell.execFile('./githook.sh',function(error,stdout){
        if (error) console.log('error ' + error)
        if (stdout) console.log('stdout ' + stdout)
      })
    }
  } else {
    ctx.body = '<h1>404</h1>'
  }
  function parsePostData() {
    return new Promise((resolve,reject)=>{
      try {
        let postData = '';
        ctx.req.addListener('data', (data)=>{
          postData += data;
        })
        ctx.req.on('end', ()=>{
          let parseData = JSON.parse(postData)
          resolve(parseData)
        })
      } catch (error) {
        reject(error)
      }
    }) 
  }
})
app.listen(3000,()=>{
  console.log("服务已经开启3000端口")
})